package Tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import Plants.PowerPlant;
import SmartGrid.ConsumerEnergyMeter;
import SmartGrid.SmartGrid;

public class SmartGridStatus {
		
	/**
	 * Sets each power plants electric output, available energy, and list of consumers to those specified in a text file.
	 * @param smartgrid a SmartGrid object which has the power plants loaded
	 * @param filename a text file that contains details of a smartgrid.  Produced by calling saveGridStatus
	 */
	public static void loadGridStatus(SmartGrid smartgrid, String filename)
	{
		FileInputStream fis;
		DataInputStream dis;
		BufferedReader br;
		try
		{
			fis = new FileInputStream(filename);
			dis = new DataInputStream(fis);
			br = new BufferedReader(new InputStreamReader(dis));
			String line;
			while( (line = br.readLine())  != null)
			{
				String[] content = line.split(" ");
				String name = content[0];
				PowerPlant p = smartgrid.getPlant(name);
				if(p == null)
				{
					Log.Write("Error in loading grid status.  Could not find power plant with name " + name);
					continue;
				}
				p.setElectricOutput(Integer.parseInt(content[1]), true);
				p.setAvailableEnergy(Integer.parseInt(content[2]), true);
				p.setResponsibilities(0, true);
				p.getConsumers().clear();
				for(int i = 3; i < content.length; i++)
				{
					ConsumerEnergyMeter consumer = new ConsumerEnergyMeter(Integer.parseInt(content[i]));
					p.addConsumer(consumer);
				}
			}
		}
		catch(Exception e)
		{
			Log.Write("Error in loading grid status.");
		}
	}
	
	/**
	 * Writes out the SmartGrid's current status to a text file
	 * @param smartgrid
	 * @param filename
	 */
	public static void saveGridStatus(SmartGrid smartgrid, String filename)
	{
		try 
		{
			BufferedWriter out = new BufferedWriter(new FileWriter(filename));
			out.write(smartgrid.toString());
			out.close();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}

}
